/*
 * @Descripttion: 
 * @version: 
 * @Author: 奇辰科技
 * @Date: 2021-09-29 09:20:52
 * @LastEditors: lokei
 * @LastEditTime: 2023-02-23 11:10:06
 */
package cn.lokei.task.service.print;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.lokei.task.entity.printer.Printer;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
// import org.apache.http.util.EntityUtils;
import org.apache.http.util.EntityUtils;

@Slf4j
@Service("feiePrintService")
public class FeiePrintService {

	public void print(Printer printer, String content) {
		// 标签说明：
		// 单标签:
		// "<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
		// "<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
		// 成对标签：
		// "<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
		// <W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
		// 拼凑订单内容时可参考如下格式
		// 根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

		// String content;
		// content = "<CB>测试打印</CB><BR>";
		// content += "名称 单价 数量 金额<BR>";
		// content += "--------------------------------<BR>";
		// content += "饭 1.0 1 1.0<BR>";
		// content += "炒饭 10.0 10 10.0<BR>";
		// content += "蛋炒饭 10.0 10 100.0<BR>";
		// content += "鸡蛋炒饭 100.0 1 100.0<BR>";
		// content += "番茄蛋炒饭 1000.0 1 100.0<BR>";
		// content += "西红柿蛋炒饭 1000.0 1 100.0<BR>";
		// content += "西红柿鸡蛋炒饭 100.0 10 100.0<BR>";
		// content += "备注：加辣<BR>";
		// content += "--------------------------------<BR>";
		// content += "合计：xx.0元<BR>";
		// content += "送货地点：广州市南沙区xx路xx号<BR>";
		// content += "联系电话：13888888888888<BR>";
		// content += "订餐时间：2016-08-08 08:08:08<BR>";
		// content += "<QR>http://www.dzist.com</QR>";

		// 通过POST请求，发送打印信息到服务器
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(30000)// 读取超时
				.setConnectTimeout(30000)// 连接超时
				.build();

		CloseableHttpClient httpClient = HttpClients.custom()
				.setDefaultRequestConfig(requestConfig)
				.build();

		HttpPost post = new HttpPost("http://api.feieyun.cn/Api/Open/");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("user", printer.getUser()));
		String STIME = String.valueOf(System.currentTimeMillis() / 1000);
		nvps.add(new BasicNameValuePair("stime", STIME));
		nvps.add(new BasicNameValuePair("sig", DigestUtils.sha1Hex(printer.getUser() + printer.getUkey() + STIME)));
		nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));// 固定值,不需要修改
		nvps.add(new BasicNameValuePair("sn", printer.getSn()));
		nvps.add(new BasicNameValuePair("content", content));
		nvps.add(new BasicNameValuePair("times", "1"));// 打印联数

		CloseableHttpResponse response = null;
		try {
			// String result = null;
			post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			Integer print_number = 1;
			if (printer.getPrint_number() != null && printer.getPrint_number() > 0) {
				print_number = printer.getPrint_number();
			}
			for (Integer i = 0; i < print_number; i++) {
				response = httpClient.execute(post);
				int statecode = response.getStatusLine().getStatusCode();
				if (statecode == 200) {
					HttpEntity httpentity = response.getEntity();
					if (httpentity != null) {
						// 服务器返回的JSON字符串，建议要当做日志记录起来
						String result = EntityUtils.toString(httpentity);
						JSONObject result_json = (JSONObject) JSON.parse(result);
						if (result_json.getIntValue("ret") != 0) {
							System.out.println(result_json.getString("msg"));
							log.info("ret: " + result_json.getString("ret") + ";" + result_json.getString("msg"));
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				post.abort();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
